//
//  ViewController.m
//  MergeVideoAndMusic
//
//  Created by huchunyuan on 15/12/3.
//  Copyright © 2015年 huchunyuan. All rights reserved.
//

#import "MergeVideoAndMusicViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface MergeVideoAndMusicViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation MergeVideoAndMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)mergeAction:(UIButton *)sender {
    [self merge];
}

- (void)merge{
    NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSURL *audioInputUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"五环之歌" ofType:@"mp3"]];
    NSURL *videoInputUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myPlayer" ofType:@"mp4"]];
    NSString *outPutFilePath = [documents stringByAppendingPathComponent:@"merge.mp4"];
    
    NSURL *outputFileUrl = [NSURL fileURLWithPath:outPutFilePath];
    CMTime nextClistartTime = kCMTimeZero;
    AVMutableComposition *comosition = [AVMutableComposition composition];
    
    AVURLAsset *videoAsset = [[AVURLAsset alloc] initWithURL:videoInputUrl options:nil];
    CMTimeRange videoTimeRange = CMTimeRangeMake(kCMTimeZero, videoAsset.duration);
    AVMutableCompositionTrack *videoTrack = [comosition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    AVAssetTrack *videoAssetTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    [videoTrack insertTimeRange:videoTimeRange ofTrack:videoAssetTrack atTime:nextClistartTime error:nil];
    
    AVURLAsset *audioAsset = [[AVURLAsset alloc] initWithURL:audioInputUrl options:nil];
    CMTimeRange audioTimeRange = videoTimeRange;
    AVMutableCompositionTrack *audioTrack = [comosition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    AVAssetTrack *audioAssetTrack = [[audioAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
    [audioTrack insertTimeRange:audioTimeRange ofTrack:audioAssetTrack atTime:nextClistartTime error:nil];
    
    AVAssetExportSession *assetExport = [[AVAssetExportSession alloc] initWithAsset:comosition presetName:AVAssetExportPresetMediumQuality];
    assetExport.outputFileType = AVFileTypeQuickTimeMovie;
    assetExport.outputURL = outputFileUrl;
    assetExport.shouldOptimizeForNetworkUse = YES;
    [assetExport exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self playWithUrl:outputFileUrl];
        });
    }];
}

- (void)playWithUrl:(NSURL *)url{
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = self.imageView.frame;
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    [self.imageView.layer addSublayer:playerLayer];
    // 播放
    [player play];
}

@end
